package com.wuwei.elearning.question.service.impl;

import com.alibaba.fastjson.JSON;
import com.wuwei.elearning.config.AiConfig;
import com.wuwei.elearning.config.factory.AiClient;
import com.wuwei.elearning.config.factory.AiClientFactory;
import com.wuwei.elearning.question.model.ChatMessage;
import com.wuwei.elearning.question.model.ChatRequest;
import com.wuwei.elearning.question.model.ChatResponse;
import com.wuwei.elearning.question.service.AiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.CompletableFuture;

@Service
@Slf4j
public class AiServiceImpl implements AiService {

    @Autowired
    private AiConfig aiConfig;
    
    @Autowired
    private AiClientFactory aiClientFactory;
    
    @Autowired(required = false)
    private RedisTemplate<String, Object> redisTemplate;
    
    // Cache key prefix for conversation history
    private static final String CONVERSATION_CACHE_PREFIX = "ai:conversation:";

    @Override
    public SseEmitter streamChatCompletion(ChatRequest request) {
        SseEmitter emitter = new SseEmitter(-1L); // No timeout
        
        try {
            log.info("开始新的AI聊天流式请求，提供商: {}", aiConfig.getProvider());
            
            // 创建一个包含新提示的所有消息列表
            List<ChatMessage> conversationHistory = new ArrayList<>();
            
            // 如果提供了用户ID，尝试获取缓存的对话
            if (request.getUserId() != null) {
                conversationHistory = getCachedConversation(request.getUserId());
                log.info("为用户 {} 加载了 {} 条缓存消息", request.getUserId(), conversationHistory.size());
            }
            
            // 如果没有缓存的对话，使用请求中的历史记录
            if (conversationHistory.isEmpty() && request.getHistory() != null) {
                conversationHistory.addAll(request.getHistory());
            }
            
            // 将新的用户消息添加到对话中
            ChatMessage userMessage = new ChatMessage("user", request.getPrompt());
            conversationHistory.add(userMessage);
            
            // 保留最终引用以进行异步处理
            final List<ChatMessage> finalHistory = new ArrayList<>(conversationHistory);
            
            // 将逐步构建的响应内容
            StringBuilder fullResponseContent = new StringBuilder();
            
            // 在单独的线程中执行流式请求
            CompletableFuture.runAsync(() -> {
                try {
                    // 获取相应的AI客户端
                    AiClient client = aiClientFactory.createClient();
                    log.info("使用 {} 进行流式聊天完成", client.getClass().getSimpleName());
                    
                    // 调用AI客户端进行流式聊天完成
                    String responseContent = client.streamChatCompletion(finalHistory, emitter, fullResponseContent);
                    
                    // 如果responseContent为null，则表示在提供商方法中直接处理了流式响应
                    if (responseContent != null) {
                        fullResponseContent.append(responseContent);
                    }
                    
                    // 创建并将助手的响应添加到对话历史记录中
                    ChatMessage assistantMessage = new ChatMessage("assistant", fullResponseContent.toString());
                    finalHistory.add(assistantMessage);
                    
                    // 如果提供了userId，则缓存更新后的对话
                    if (request.getUserId() != null) {
                        cacheConversation(request.getUserId(), finalHistory);
                    }
                    
                    // 如果尚未在提供商特定代码中完成，则发送最终响应并完成
                    if (responseContent != null) {
                        ChatResponse finalResponse = new ChatResponse();
                        finalResponse.setContent(fullResponseContent.toString());
                        finalResponse.setIsComplete(true);
                        emitter.send(finalResponse);
                    }
                    
                    emitter.complete();
                    
                } catch (Exception e) {
                    log.error("AI流式响应错误", e);
                    try {
                        ChatResponse errorResponse = new ChatResponse();
                        errorResponse.setContent("错误: " + e.getMessage());
                        errorResponse.setIsComplete(true);
                        emitter.send(errorResponse);
                        emitter.complete();
                    } catch (IOException ex) {
                        log.error("发送错误响应时出错", ex);
                        emitter.completeWithError(e);
                    }
                }
            });
            
            return emitter;
            
        } catch (Exception e) {
            log.error("设置聊天完成时出错", e);
            emitter.completeWithError(e);
            return emitter;
        }
    }


    @Override
    public List<ChatMessage> getCachedConversation(String userId) {
        if (userId == null || userId.isEmpty() || redisTemplate == null) {
            log.debug("跳过缓存查找: userId为空或Redis不可用");
            return new ArrayList<>();
        }
        
        try {
            String cacheKey = CONVERSATION_CACHE_PREFIX + userId;
            
            // 尝试从Redis缓存获取
            Object cachedData = redisTemplate.opsForValue().get(cacheKey);
            
            if (cachedData instanceof String) {
                // 如果是JSON字符串，解析它
                try {
                    return JSON.parseArray((String) cachedData, ChatMessage.class);
                } catch (Exception e) {
                    log.error("解析用户 {} 的缓存对话时出错", userId, e);
                }
            } else if (cachedData instanceof List) {
                // 如果已经是列表，尝试转换它
                try {
                    @SuppressWarnings("unchecked")
                    List<ChatMessage> messages = (List<ChatMessage>) cachedData;
                    return messages;
                } catch (ClassCastException e) {
                    log.error("转换用户 {} 的缓存对话时出错", userId, e);
                }
            }
        } catch (Exception e) {
            log.warn("访问Redis缓存时出错: {}", e.getMessage());
        }
        
        return new ArrayList<>();
    }

    @Override
    public void cacheConversation(String userId, List<ChatMessage> messages) {
        if (userId == null || userId.isEmpty() || messages == null || redisTemplate == null) {
            log.debug("跳过缓存存储: userId/messages为空或Redis不可用");
            return;
        }
        
        try {
            String cacheKey = CONVERSATION_CACHE_PREFIX + userId;
            
            // 转换为JSON字符串进行存储
            String jsonData = JSON.toJSONString(messages);
            
            // 存储在Redis中，使用基于配置的TTL
            redisTemplate.opsForValue().set(cacheKey, jsonData);
            redisTemplate.expire(cacheKey, java.time.Duration.ofSeconds(aiConfig.getTokenCacheTimeSeconds()));
            
            log.info("为用户 {} 缓存了 {} 条消息，TTL {} 秒", 
                    messages.size(), userId, aiConfig.getTokenCacheTimeSeconds());
        } catch (Exception e) {
            log.warn("存储对话到Redis时出错: {}", e.getMessage());
        }
    }
} 